using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Csharp01._1118;

namespace Csharp01.TuShuGuanLi
{
    public partial class BookDeleteForm : Form
    {
        public BookDeleteForm()
        {
            InitializeComponent();
            LoadCategories();
            LoadAllBooks();
        }

        private void InitializeComponent()
        {
            this.panel1 = new System.Windows.Forms.Panel();
            this.btnQuery = new System.Windows.Forms.Button();
            this.txtKeyword = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.cboCategory = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.btnDelete = new System.Windows.Forms.Button();
            this.dgvBooks = new System.Windows.Forms.DataGridView();
            this.panel1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dgvBooks)).BeginInit();
            this.SuspendLayout();
            // 
            // panel1
            // 
            this.panel1.Controls.Add(this.btnDelete);
            this.panel1.Controls.Add(this.btnQuery);
            this.panel1.Controls.Add(this.txtKeyword);
            this.panel1.Controls.Add(this.label2);
            this.panel1.Controls.Add(this.cboCategory);
            this.panel1.Controls.Add(this.label1);
            this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
            this.panel1.Location = new System.Drawing.Point(0, 0);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(800, 70);
            this.panel1.TabIndex = 0;
            // 
            // btnQuery
            // 
            this.btnQuery.Location = new System.Drawing.Point(650, 25);
            this.btnQuery.Name = "btnQuery";
            this.btnQuery.Size = new System.Drawing.Size(75, 23);
            this.btnQuery.TabIndex = 4;
            this.btnQuery.Text = "查询";
            this.btnQuery.UseVisualStyleBackColor = true;
            this.btnQuery.Click += new System.EventHandler(this.btnQuery_Click);
            // 
            // txtKeyword
            // 
            this.txtKeyword.Location = new System.Drawing.Point(420, 27);
            this.txtKeyword.Name = "txtKeyword";
            this.txtKeyword.Size = new System.Drawing.Size(200, 21);
            this.txtKeyword.TabIndex = 3;
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(360, 30);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(59, 12);
            this.label2.TabIndex = 2;
            this.label2.Text = "关键字查询:";
            // 
            // cboCategory
            // 
            this.cboCategory.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboCategory.FormattingEnabled = true;
            this.cboCategory.Location = new System.Drawing.Point(120, 27);
            this.cboCategory.Name = "cboCategory";
            this.cboCategory.Size = new System.Drawing.Size(200, 20);
            this.cboCategory.TabIndex = 1;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(40, 30);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(59, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "分类查询:";
            // 
            // btnDelete
            // 
            this.btnDelete.Location = new System.Drawing.Point(730, 25);
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.Size = new System.Drawing.Size(75, 23);
            this.btnDelete.TabIndex = 5;
            this.btnDelete.Text = "删除";
            this.btnDelete.UseVisualStyleBackColor = true;
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            // 
            // dgvBooks
            // 
            this.dgvBooks.AllowUserToAddRows = false;
            this.dgvBooks.AllowUserToDeleteRows = false;
            this.dgvBooks.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgvBooks.Dock = System.Windows.Forms.DockStyle.Fill;
            this.dgvBooks.Location = new System.Drawing.Point(0, 70);
            this.dgvBooks.Name = "dgvBooks";
            this.dgvBooks.ReadOnly = true;
            this.dgvBooks.RowTemplate.Height = 23;
            this.dgvBooks.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
            this.dgvBooks.Size = new System.Drawing.Size(800, 380);
            this.dgvBooks.TabIndex = 1;
            // 
            // BookDeleteForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(800, 450);
            this.Controls.Add(this.dgvBooks);
            this.Controls.Add(this.panel1);
            this.Name = "BookDeleteForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "删除图书";
            this.panel1.ResumeLayout(false);
            this.panel1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dgvBooks)).EndInit();
            this.ResumeLayout(false);
        }

        private Panel panel1;
        private Button btnQuery;
        private TextBox txtKeyword;
        private Label label2;
        private ComboBox cboCategory;
        private Label label1;
        private DataGridView dgvBooks;
        private Button btnDelete;

        private void LoadCategories()
        {
            try
            {
                using (var connection = Connection.GetMySqlConnection())
                {
                    connection.Open();
                    string sql = "SELECT DISTINCT book_category FROM book_info ORDER BY book_category";
                    using (var command = new MySqlCommand(sql, connection))
                    {
                        using (var reader = command.ExecuteReader())
                        {
                            DataTable dt = new DataTable();
                            dt.Columns.Add("book_category", typeof(string));
                            dt.Rows.Add("--全部分类--");

                            while (reader.Read())
                            {
                                dt.Rows.Add(reader.GetString("book_category"));
                            }

                            cboCategory.DataSource = dt;
                            cboCategory.DisplayMember = "book_category";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载图书分类失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadAllBooks()
        {
            try
            {
                using (var connection = Connection.GetMySqlConnection())
                {
                    connection.Open();
                    string sql = @"
                        SELECT b.book_id, b.isbn, b.book_name, b.author, p.publisher_name, b.publish_date, 
                               b.book_category, b.book_price, 
                               CASE WHEN b.book_status = 1 THEN '在馆' ELSE '借出' END as status
                        FROM book_info b
                        JOIN publisher_info p ON b.publisher_id = p.publisher_id
                        ORDER BY b.book_id";

                    using (var command = new MySqlCommand(sql, connection))
                    {
                        using (var adapter = new MySqlDataAdapter(command))
                        {
                            DataTable dt = new DataTable();
                            adapter.Fill(dt);
                            dgvBooks.DataSource = dt;
                            
                            // 设置列标题
                            dgvBooks.Columns["book_id"].HeaderText = "ID";
                            dgvBooks.Columns["isbn"].HeaderText = "ISBN";
                            dgvBooks.Columns["book_name"].HeaderText = "书名";
                            dgvBooks.Columns["author"].HeaderText = "作者";
                            dgvBooks.Columns["publisher_name"].HeaderText = "出版社";
                            dgvBooks.Columns["publish_date"].HeaderText = "出版日期";
                            dgvBooks.Columns["book_category"].HeaderText = "分类";
                            dgvBooks.Columns["book_price"].HeaderText = "价格";
                            dgvBooks.Columns["status"].HeaderText = "状态";
                            
                            // 设置列宽度
                            dgvBooks.Columns["book_id"].Width = 50;
                            dgvBooks.Columns["isbn"].Width = 120;
                            dgvBooks.Columns["book_name"].Width = 150;
                            dgvBooks.Columns["author"].Width = 100;
                            dgvBooks.Columns["publisher_name"].Width = 120;
                            dgvBooks.Columns["publish_date"].Width = 80;
                            dgvBooks.Columns["book_category"].Width = 100;
                            dgvBooks.Columns["book_price"].Width = 60;
                            dgvBooks.Columns["status"].Width = 60;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载图书信息失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                using (var connection = Connection.GetMySqlConnection())
                {
                    connection.Open();
                    
                    string sql = @"
                        SELECT b.book_id, b.isbn, b.book_name, b.author, p.publisher_name, b.publish_date, 
                               b.book_category, b.book_price, 
                               CASE WHEN b.book_status = 1 THEN '在馆' ELSE '借出' END as status
                        FROM book_info b
                        JOIN publisher_info p ON b.publisher_id = p.publisher_id
                        WHERE 1=1";
                    
                    if (cboCategory.SelectedIndex > 0)
                    {
                        sql += " AND b.book_category = @category";
                    }
                    
                    if (!string.IsNullOrWhiteSpace(txtKeyword.Text))
                    {
                        sql += " AND (b.book_name LIKE @keyword OR b.author LIKE @keyword OR b.isbn LIKE @keyword)";
                    }
                    
                    sql += " ORDER BY b.book_id";

                    using (var command = new MySqlCommand(sql, connection))
                    {
                        if (cboCategory.SelectedIndex > 0)
                        {
                            command.Parameters.AddWithValue("@category", cboCategory.SelectedValue);
                        }
                        
                        if (!string.IsNullOrWhiteSpace(txtKeyword.Text))
                        {
                            command.Parameters.AddWithValue("@keyword", "%" + txtKeyword.Text.Trim() + "%");
                        }

                        using (var adapter = new MySqlDataAdapter(command))
                        {
                            DataTable dt = new DataTable();
                            adapter.Fill(dt);
                            dgvBooks.DataSource = dt;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询图书失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            // 检查是否有选中行
            if (dgvBooks.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要删除的图书！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 获取选中行的数据
            DataGridViewRow selectedRow = dgvBooks.SelectedRows[0];
            int bookId = Convert.ToInt32(selectedRow.Cells["book_id"].Value);
            string bookName = selectedRow.Cells["book_name"].Value.ToString();

            // 确认删除
            DialogResult result = MessageBox.Show($"确定要删除图书《{bookName}》吗？\n此操作不可撤销！", "确认删除", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            
            if (result == DialogResult.Yes)
            {
                try
                {
                    using (var connection = Connection.GetMySqlConnection())
                    {
                        connection.Open();
                        
                        // 删除图书记录
                        string sql = "DELETE FROM book_info WHERE book_id = @book_id";
                        using (var command = new MySqlCommand(sql, connection))
                        {
                            command.Parameters.AddWithValue("@book_id", bookId);
                            int rowsAffected = command.ExecuteNonQuery();
                            
                            if (rowsAffected > 0)
                            {
                                MessageBox.Show("图书删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                // 重新加载数据
                                btnQuery_Click(sender, e);
                            }
                            else
                            {
                                MessageBox.Show("图书删除失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除图书时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
}
